package com.sudo.api._admin;

import com.sudo.common.annotation.ApiIdempotent;
import com.sudo.common.annotation.ApiAuthorization;
import com.sudo.common.task.TaskMethod;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.dao.admin.entity.SysServerNode;
import com.sudo.dao.admin.model.bo.SysServerNodeTaskBO;
import com.sudo.rpc.api.service.RmiSetServerService;
import com.sudo.rpc.api.utils.RpcRes;
import com.sudo.service.admin.service.SysServerNodeService;
import com.sudo.service.admin.service.SysServerNodeTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.rmi.RemoteException;
import java.util.Map;

@Slf4j
@Api(value = "Rpc定时Task接口",tags = {"Rpc定时Task管理相关的接口"})
@RestController
@RequestMapping("sysServerNodeTask")
public class SysServerNodeTaskController extends AdminBaseController{

    @Resource
    private SysServerNodeTaskService sysServerNodeTaskService;

    @Resource
    private SysServerNodeService sysServerNodeService;

    @Resource
    private RmiSetServerService rmiSetServerService;


    @ApiOperation(value = "分页查询Rpc定时任务",notes = "分页查询Rpc定时任务",httpMethod = "GET")
    @GetMapping("/querySysServerNodeTaskMap")
    public JsonRes querySysServerNodeJobByPage() {
        Map<String,Map<String, Map<String, TaskMethod>>> serverNodeTaskMap = sysServerNodeTaskService.getServerNodeTaskMap();
        return JsonRes.ok(serverNodeTaskMap);
    }

    @ApiIdempotent
    @ApiAuthorization(menu = "server_node",button = "pullTask")
    @ApiOperation(value = "拉取Rpc任务列表",notes = "拉取Rpc任务列表",httpMethod = "GET")
    @GetMapping("/pullSysServerNodeTask")
    public JsonRes pullSysServerNodeTask(@RequestParam Integer id) throws RemoteException {
        SysServerNode serverNode = sysServerNodeService.getServerNodeById(id);
        if (serverNode != null){
            String[] split = serverNode.getServer().split(":");
            RpcRes pullServer = (RpcRes)rmiSetServerService.pullServer(split[0], Integer.parseInt(split[1]));
            if (pullServer.getData() == null){
                return JsonRes.errorMsg("该服务节点没有任务");
            }
            int affectCount = sysServerNodeTaskService.analysisAndSaveServerNodeTask(serverNode,pullServer.getData());
            return JsonRes.ok(affectCount);
        }else {
            return JsonRes.errorMsg("服务节点不存在");
        }
    }

    @ApiAuthorization(menu = "server_node",button = "taskList")
    @ApiOperation(value = "拉取Rpc任务列表",notes = "拉取Rpc任务列表",httpMethod = "GET")
    @PostMapping("/querySysServerNodeTaskByPage")
    public JsonRes querySysServerNodeTaskByPage(@RequestBody SysServerNodeTaskBO sysServerNodeTaskBO) {
        PagedGridResult pagedGridResult = sysServerNodeTaskService.querySysServerNodeTaskByPage(sysServerNodeTaskBO);
        return JsonRes.ok(pagedGridResult);
    }
}
